package org.javaweb.cms_web.controller;

import org.javaweb.cms_web.model.Team;
import org.javaweb.cms_web.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.javaweb.cms_web.service.TeamService;
import org.javaweb.cms_web.service.UserService;

import java.util.List;

@Controller
public class TeamController {

    @Autowired
    private TeamService teamService;

    @Autowired
    private UserService userService;

    // 显示所有团队列表，并允许搜索
    @GetMapping("/viewTeams")
    public String showTeamsList(
            @RequestParam(value = "search", required = false) String search,
            Model model) {
        // 如果没有传入 search 参数，默认查询所有团队
        if (search == null || search.trim().isEmpty()) {
            search = null;
        }

        List<Team> teams = teamService.getTeamsBySearch(search);  // 使用服务方法进行模糊查询

        System.out.println("团队：" + teams);
        teams.forEach(team -> {
            System.out.println("团队 ID: " + team.getTeamId());
            System.out.println("团队名称: " + team.getTeamName());
            System.out.println("研究方向: " + team.getResearchField());
            System.out.println("团队简介: " + team.getDescription());
            System.out.println("创建时间: " + team.getCreationTime());
        });
        model.addAttribute("teams", teams);
        return "viewTeams";  // 返回团队列表视图
    }

    // 显示团队详情
    @GetMapping("/teamDetails/{teamId}")
    public String showTeamDetails(@PathVariable("teamId") int teamId, Model model) {
        Team team = teamService.getTeamById(teamId);
        List<String> members = teamService.getTeamMembers(teamId);  // 获取团队成员

        model.addAttribute("team", team);
        model.addAttribute("members", members);
        model.addAttribute("teamId", teamId);  // 将团队ID传递到页面，方便后续跳转

        return "viewTeamDetails";  // 返回团队详情视图
    }

    // 显示成员详情
    @GetMapping("/memberDetails")
    public String showMemberDetails(@RequestParam("name") String name, Model model) {
        // 根据成员名称从 user 表中查询对应的用户信息
        User user = userService.findUserByName(name);

        if (user == null) {
            model.addAttribute("errorMessage", "未找到对应的用户信息");
            return "errorPage"; // 如果未找到，跳转到错误页面
        }
        model.addAttribute("teamId", user.getTeamId());  // 将团队ID传递到页面
        model.addAttribute("user", user);  // 将用户信息添加到模型中
        return "viewMemberDetails";       // 跳转到成员详情 JSP 页面
    }
}
